'
' Will Strohl (will.strohl@gmail.com)
' http://www.willstrohl.com
'
'Copyright (c) 2012, Will Strohl
'All rights reserved.
'
'Redistribution and use in source and binary forms, with or without modification, are 
'permitted provided that the following conditions are met:
'
'Redistributions of source code must retain the above copyright notice, this list of 
'conditions and the following disclaimer.
'
'Redistributions in binary form must reproduce the above copyright notice, this list 
'of conditions and the following disclaimer in the documentation and/or other 
'materials provided with the distribution.
'
'Neither the name of Will Strohl, Simple Redirect, nor the names of its contributors may be 
'used to endorse or promote products derived from this software without specific prior 
'written permission.
'
'THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
'EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
'OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
'SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
'INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
'TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR 
'BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
'CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
'ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH 
'DAMAGE.
'

Imports DotNetNuke.UI.Skins.Controls
Imports DotNetNuke.Entities.Modules
Imports System.Text.RegularExpressions
Imports WillStrohl.Modules.SimpleRedirect.RedirectController

Namespace WillStrohl.Modules.SimpleRedirect

    ''' -----------------------------------------------------------------------------
    ''' <summary>
    ''' The ViewSimpleRedirect class displays the content
    ''' </summary>
    ''' <remarks>
    ''' </remarks>
    ''' <history>
    ''' </history>
    ''' -----------------------------------------------------------------------------
    Partial Class View
        Inherits SimpleRedirectModuleBase
        Implements IActionable

#Region " Private Members "

        Private Const HTTP301_VALUE As Integer = 301
        Private Const HTTP301_TEXT As String = "Moved Permanently"
        Private Const CACHEKEY_PAGE_FORMAT As String = "WillStrohl-SimpleRedirect-{0}"
        Private Const CACHEVALUE_IGNORE As String = "ignore"
        Private Const GRID_TR_OPEN As String = "<tr>"
        Private Const GRID_TR_CLOSE As String = "</tr>"
        Private Const GRID_ITEM_PATTERN As String = "<td class=""dnnGridItem NormalBold"">{0}:</td><td class=""dnnGridItem"">{1}</td>"
        Private Const GRID_ALT_ITEM_PATTERN As String = "<td class=""dnnGridAltItem NormalBold"">{0}:</td><td class=""dnnGridAltItem"">{1}</td>"

        Private p_Enabled As Nullable(Of Boolean)
        Private p_TrackingEnabled As Nullable(Of Boolean)

#End Region

#Region " Private Properties "

        Private ReadOnly Property Enabled As Boolean
            Get
                If Not p_Enabled.HasValue Then
                    If Not Settings(SETTING_ENABLE) Is Nothing Then
                        p_Enabled = Boolean.Parse(Settings(SETTING_ENABLE).ToString())
                    Else
                        p_Enabled = True
                    End If
                Else
                    p_Enabled = True
                End If

                Return p_Enabled
            End Get
        End Property

        Private ReadOnly Property TrackingEnabled As Boolean
            Get
                If Not p_TrackingEnabled.HasValue Then
                    If Not Settings(SETTING_TRACKING) Is Nothing Then
                        p_TrackingEnabled = Boolean.Parse(Settings(SETTING_TRACKING).ToString())
                    Else
                        p_TrackingEnabled = True
                    End If
                Else
                    p_TrackingEnabled = True
                End If

                Return p_TrackingEnabled
            End Get
        End Property

#End Region

#Region " Event Handlers "

        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Page_Load runs when the control is loaded
        ''' </summary>
        ''' <remarks>
        ''' </remarks>
        ''' <history>
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Try
                If Not Page.IsPostBack Then
                    BindData()
                End If

                If Not IsEditable AndAlso PortalSettings.UserMode <> Portals.PortalSettings.Mode.Edit Then
                    ContainerControl.Visible = False
                End If
            Catch exc As Exception        'Module failed to load
                ProcessModuleLoadException(Me, exc)
            End Try
        End Sub

#End Region

#Region " Helper Methods "

        Private Sub BindData()

            If Enabled Then

                InitializeRedirect()

                InitializeDebug()

            Else

                DotNetNuke.UI.Skins.Skin.AddModuleMessage(Me, GetLocalizedString("ModuleDisabled.Text"), ModuleMessage.ModuleMessageType.YellowWarning)

            End If

        End Sub

        Private Sub LocalizeModule()

            ' do nothing

        End Sub

        Private Sub InitializeDebug()

            Dim blnDebug As Boolean = False
            If Not Settings(SETTING_DEBUG) Is Nothing Then
                blnDebug = Boolean.Parse(Settings(SETTING_DEBUG))
            End If

            If blnDebug Then

                Dim sb As New StringBuilder
                Dim strCurrentUrl As String = String.Format("{0}://{1}{2}", Request.Url.Scheme, PortalSettings.PortalAlias.HTTPAlias, Request.RawUrl)

                sb.AppendFormat("<div class=""dnnFormMessage dnnFormWarning"">{0}</div>", GetLocalizedString("DebugHeader.Warning"))
                sb.Append("<table class=""dnnGrid wnsRedirectDebugGrid dnnClear"">")
                sb.Append(GRID_TR_OPEN)
                sb.AppendFormat(GRID_ITEM_PATTERN, GetLocalizedString("Debug.CurrentCombinedUrl"), strCurrentUrl)
                sb.Append(GRID_TR_CLOSE)

                Dim ctlModule As New RedirectController
                Dim oRedirect As RedirectInfo = ctlModule.GetRedirectByUrl(strCurrentUrl)
                Dim blnHasRedirect As Boolean = (Not oRedirect Is Nothing)

                sb.Append(GRID_TR_OPEN)
                sb.AppendFormat(GRID_ALT_ITEM_PATTERN, GetLocalizedString("Debug.HasRedirectRule"), blnHasRedirect)
                sb.Append(GRID_TR_CLOSE)

                sb.Append(GRID_TR_OPEN)
                sb.AppendFormat(GRID_ITEM_PATTERN, GetLocalizedString("Debug.Enabled"), Enabled)
                sb.Append(GRID_TR_CLOSE)
                sb.Append(GRID_TR_OPEN)
                sb.AppendFormat(GRID_ALT_ITEM_PATTERN, GetLocalizedString("Debug.Tracking"), TrackingEnabled)
                sb.Append(GRID_TR_CLOSE)

                'sb.Append(GRID_TR_OPEN)
                'sb.AppendFormat(GRID_ITEM_PATTERN, GetLocalizedString("Debug.ResponseCode"), Response.StatusCode)
                'sb.Append(GRID_TR_CLOSE)

                'sb.Append(GRID_TR_OPEN)
                'sb.AppendFormat(GRID_ALT_ITEM_PATTERN, GetLocalizedString("Debug.AbsolutePath"), Request.Url.AbsolutePath)
                'sb.Append(GRID_TR_CLOSE)
                'sb.Append(GRID_TR_OPEN)
                'sb.AppendFormat(GRID_ITEM_PATTERN, GetLocalizedString("Debug.AbsoluteUri"), Request.Url.AbsoluteUri)
                'sb.Append(GRID_TR_CLOSE)
                'sb.Append(GRID_TR_OPEN)
                'sb.AppendFormat(GRID_ALT_ITEM_PATTERN, GetLocalizedString("Debug.ApplicationPath"), Request.ApplicationPath)
                'sb.Append(GRID_TR_CLOSE)
                'sb.Append(GRID_TR_OPEN)
                'sb.AppendFormat(GRID_ITEM_PATTERN, GetLocalizedString("Debug.Authority"), Request.Url.Authority)
                'sb.Append(GRID_TR_CLOSE)
                'sb.Append(GRID_TR_OPEN)
                'sb.AppendFormat(GRID_ALT_ITEM_PATTERN, GetLocalizedString("Debug.CurrentExecutionFilePath"), Request.CurrentExecutionFilePath)
                'sb.Append(GRID_TR_CLOSE)
                'sb.Append(GRID_TR_OPEN)
                'sb.AppendFormat(GRID_ITEM_PATTERN, GetLocalizedString("Debug.DnsSafeHost"), Request.Url.DnsSafeHost)
                'sb.Append(GRID_TR_CLOSE)
                'sb.Append(GRID_TR_OPEN)
                'sb.AppendFormat(GRID_ALT_ITEM_PATTERN, GetLocalizedString("Debug.DnnCommonApplicationPath"), DotNetNuke.Common.ApplicationPath)
                'sb.Append(GRID_TR_CLOSE)
                'sb.Append(GRID_TR_OPEN)
                'sb.AppendFormat(GRID_ITEM_PATTERN, GetLocalizedString("Debug.DnnCommonApplicationUrl"), DotNetNuke.Common.ApplicationURL())
                'sb.Append(GRID_TR_CLOSE)
                'sb.Append(GRID_TR_OPEN)
                'sb.AppendFormat(GRID_ALT_ITEM_PATTERN, GetLocalizedString("Debug.DnnPortalHttpAlias"), PortalSettings.PortalAlias.HTTPAlias)
                'sb.Append(GRID_TR_CLOSE)
                'sb.Append(GRID_TR_OPEN)
                'sb.AppendFormat(GRID_ITEM_PATTERN, GetLocalizedString("Debug.FilePath"), Request.FilePath)
                'sb.Append(GRID_TR_CLOSE)
                'sb.Append(GRID_TR_OPEN)
                'sb.AppendFormat(GRID_ALT_ITEM_PATTERN, GetLocalizedString("Debug.Fragment"), Request.Url.Fragment)
                'sb.Append(GRID_TR_CLOSE)
                'sb.Append(GRID_TR_OPEN)
                'sb.AppendFormat(GRID_ITEM_PATTERN, GetLocalizedString("Debug.Host"), Request.Url.Host)
                'sb.Append(GRID_TR_CLOSE)
                'sb.Append(GRID_TR_OPEN)
                'sb.AppendFormat(GRID_ALT_ITEM_PATTERN, GetLocalizedString("Debug.HttpMethod"), Request.HttpMethod)
                'sb.Append(GRID_TR_CLOSE)
                'sb.Append(GRID_TR_OPEN)
                'sb.AppendFormat(GRID_ITEM_PATTERN, GetLocalizedString("Debug.LocalPath"), Request.Url.LocalPath)
                'sb.Append(GRID_TR_CLOSE)
                'sb.Append(GRID_TR_OPEN)
                'sb.AppendFormat(GRID_ALT_ITEM_PATTERN, GetLocalizedString("Debug.OriginalString"), Request.Url.OriginalString)
                'sb.Append(GRID_TR_CLOSE)
                'sb.Append(GRID_TR_OPEN)
                'sb.AppendFormat(GRID_ITEM_PATTERN, GetLocalizedString("Debug.Path"), Request.Path)
                'sb.Append(GRID_TR_CLOSE)
                'sb.Append(GRID_TR_OPEN)
                'sb.AppendFormat(GRID_ALT_ITEM_PATTERN, GetLocalizedString("Debug.PathAndQuery"), Request.Url.PathAndQuery)
                'sb.Append(GRID_TR_CLOSE)
                'sb.Append(GRID_TR_OPEN)
                'sb.AppendFormat(GRID_ITEM_PATTERN, GetLocalizedString("Debug.PathInfo"), Request.PathInfo)
                'sb.Append(GRID_TR_CLOSE)
                'sb.Append(GRID_TR_OPEN)
                'sb.AppendFormat(GRID_ALT_ITEM_PATTERN, GetLocalizedString("Debug.PhysicalApplicationPath"), Request.PhysicalApplicationPath)
                'sb.Append(GRID_TR_CLOSE)
                'sb.Append(GRID_TR_OPEN)
                'sb.AppendFormat(GRID_ITEM_PATTERN, GetLocalizedString("Debug.PhysicalPath"), Request.PhysicalPath)
                'sb.Append(GRID_TR_CLOSE)
                'sb.Append(GRID_TR_OPEN)
                'sb.AppendFormat(GRID_ALT_ITEM_PATTERN, GetLocalizedString("Debug.Port"), Request.Url.Port)
                'sb.Append(GRID_TR_CLOSE)
                'sb.Append(GRID_TR_OPEN)
                'sb.AppendFormat(GRID_ITEM_PATTERN, GetLocalizedString("Debug.Query"), Request.Url.Query)
                'sb.Append(GRID_TR_CLOSE)
                'sb.Append(GRID_TR_OPEN)
                'sb.AppendFormat(GRID_ALT_ITEM_PATTERN, GetLocalizedString("Debug.RawUrl"), Request.RawUrl)
                'sb.Append(GRID_TR_CLOSE)
                'sb.Append(GRID_TR_OPEN)
                'sb.AppendFormat(GRID_ITEM_PATTERN, GetLocalizedString("Debug.Scheme"), Request.Url.Scheme)
                'sb.Append(GRID_TR_CLOSE)
                'sb.Append(GRID_TR_OPEN)
                'sb.AppendFormat(GRID_ALT_ITEM_PATTERN, GetLocalizedString("Debug.UserHostName"), Request.UserHostName)
                'sb.Append(GRID_TR_CLOSE)
                'sb.Append(GRID_TR_OPEN)
                'sb.AppendFormat(GRID_ITEM_PATTERN, GetLocalizedString("Debug.UserInfo"), Request.Url.UserInfo)
                'sb.Append(GRID_TR_CLOSE)
                sb.Append("</table>")

                lblDebug.Text = sb.ToString()

            Else

                lblDebug.Visible = False

            End If

        End Sub

        Private Sub InitializeRedirect()

            Dim strCurrentUrl As String = String.Concat(Request.Url.Scheme, "://", PortalSettings.PortalAlias.HTTPAlias, Request.RawUrl)
            Dim strCacheKey As String = String.Format(CACHEKEY_PAGE_FORMAT, strCurrentUrl)

            ' do not process if the current URL should not be parsed
            If Not IsValidRequest(strCurrentUrl) Then
                Exit Sub
            End If

            ' check to see if the redirect is in cache
            If Not DataCache.GetCache(strCacheKey) Is Nothing Then
                Dim strValue As String = DataCache.GetCache(strCacheKey).ToString()

                If String.Equals(strValue, CACHEVALUE_IGNORE) Then
                    Exit Sub
                Else
                    ' if found, redirect
                    RedirectToLocation(strValue)
                End If
            End If

            Dim ctlModule As New RedirectController
            Dim collRedirect As RedirectInfoCollection = ctlModule.GetRedirects(ModuleId)

            ' prevent a NullReferenceException
            If Not collRedirect Is Nothing AndAlso collRedirect.Count > 0 Then

                ' iterate through the saved redirects
                For Each oRedirect As RedirectInfo In collRedirect

                    If String.Equals(strCurrentUrl, oRedirect.RedirectFrom) Then
                        ' save to cache first
                        DataCache.SetCache(strCacheKey, oRedirect.RedirectTo)
                        ' if there is a match between the current URL, redirect
                        RedirectToLocation(oRedirect)
                        Exit Sub
                    End If

                Next

                ' save non-redirects to cache as well, to prevent unnecessary processing
                DataCache.SetCache(strCacheKey, CACHEVALUE_IGNORE)

            End If

        End Sub

        Private Sub RedirectToLocation(ByVal RedirectTo As String)

            If Not String.IsNullOrEmpty(RedirectTo) Then

                Dim ctlModule As New RedirectController
                Dim oRedirect As RedirectInfo = ctlModule.GetRedirectByUrl(RedirectTo)

                If Not oRedirect Is Nothing Then

                    RedirectToLocation(oRedirect)

                End If

            End If

        End Sub

        Private Sub RedirectToLocation(ByVal oRedirect As RedirectInfo)

            If oRedirect Is Nothing Then
                Throw New ArgumentNullException("oRedirect", "The SimpleRedirect object cannot be null when redirecting to a new URL.")
            End If

            Dim blnTrack As Boolean = False
            If Not Settings(SETTING_TRACKING) Is Nothing Then
                Try
                    blnTrack = Boolean.Parse(Settings(SETTING_TRACKING).ToString())
                Catch exTrack As Exception
                    LogException(exTrack)
                    blnTrack = False
                End Try
            End If

            If blnTrack Then
                Try
                    Dim ctlModule As New RedirectController
                    ctlModule.AddVisitor(oRedirect.RedirectId, Request.UrlReferrer.OriginalString, Request.UrlReferrer.Host)
                Catch exSave As Exception
                    LogException(exSave)
                End Try
            End If

            Response.StatusCode = HTTP301_VALUE
            Response.StatusDescription = HTTP301_TEXT
            Response.RedirectLocation = oRedirect.RedirectTo
            HttpContext.Current.ApplicationInstance.CompleteRequest()

        End Sub

        Private Function IsValidRequest(ByVal CurrentUrl As String)

            Return Not Regex.IsMatch(CurrentUrl, INVALID_REQUEST_PATCH_MATCH_PATTERN, RegexOptions.IgnoreCase)

        End Function

#End Region

#Region " Optional Interfaces "

        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Registers the module actions required for interfacing with the portal framework
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        ''' <history>
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Public ReadOnly Property ModuleActions() As Entities.Modules.Actions.ModuleActionCollection Implements Entities.Modules.IActionable.ModuleActions
            Get
                Dim Actions As New Actions.ModuleActionCollection
                Dim strEditUrl As String = EditUrl(String.Empty, String.Empty, "Edit")
                Actions.Add(GetNextActionID, _
                    Localization.GetString(Entities.Modules.Actions.ModuleActionType.AddContent, LocalResourceFile), _
                    Entities.Modules.Actions.ModuleActionType.AddContent, _
                    String.Empty, String.Empty, _
                    strEditUrl, _
                    False, DotNetNuke.Security.SecurityAccessLevel.Edit, True, False)
                Return Actions
            End Get
        End Property

#End Region

    End Class

End Namespace